import rqdatac as rq
import pandas as pd
import matplotlib.pyplot as plt

if not rq.initialized():
     rq.init("13570866213", "39314656")

all_is = rq.all_instruments(type="Future", market="cn")
sec_id = "P"
sec_ins = all_is.loc[all_is["underlying_symbol"]==sec_id]
sec_ins = sec_ins.sort_values(by="listed_date")
sec_ins.reset_index(inplace=True,drop=True)
order_ids = sec_ins["order_book_id"].to_list()
order_ids = order_ids[5:]

price_df = rq.get_price(order_ids, start_date="2000-1-4", end_date="2023-4-1", fields="close", expect_df=False)

price_df2 = pd.DataFrame(index=price_df.index)
for order_id in order_ids:
    id_data = price_df[order_id]
    id_data = id_data[30:]
    price_df2[order_id] = id_data

id0 = order_ids.pop(0)
r_df = pd.DataFrame()
for order_id in order_ids:
    r_df[id0] = abs(price_df2[order_id] - price_df2[id0])
    id0 = order_id
spread = r_df.mean(axis=1)
spread_dif = spread.shift(1) - spread
spread_dif.to_csv(f"d:\\{sec_id}_spread_dif.csv")
spread.to_csv(f"d:\\{sec_id}_spread.csv")